package com.villaday.idf.adapter;

import androidx.annotation.NonNull;

import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.villaday.idf.R;
import com.villaday.idf.model3.SleepEntity;

import java.util.List;

public class SleepTopAdapter extends RecyclerView.Adapter<SleepTopAdapter.ViewHolder> {

    private List<SleepEntity.BodyBean.TemplateListBean> data;
    private View.OnClickListener onClickListener;

    public SleepTopAdapter(List<SleepEntity.BodyBean.TemplateListBean> data, View.OnClickListener onClickListener) {
        this.data = data;
        this.onClickListener = onClickListener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View v = inflater.inflate(R.layout.recycle_sleep_top, parent, false);
        return new ViewHolder(v);
    }


    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        String imageUrl = data.get(position).getPoster();
        if (!imageUrl.equals(holder.itemView.getTag())) {//解决图片加载不闪烁的问题,可以在加载时候，对于已经加载过的item,  采用比对tag方式判断是否需要重新计算高度

            holder.itemView.setTag(null);
            RoundedCorners roundedCorners = new RoundedCorners(10);
            //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
            // RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(300, 300);
            RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);

            Glide.with(holder.itemView.getContext())
                    .load(data.get(position).getPoster())
//                    .apply(options)
                    .apply(new RequestOptions().placeholder(R.drawable.ic_replace_0))
                    .into(holder.image);
            //if (holder.itemView.getTag()==null){
            holder.itemView.setTag(imageUrl);
            holder.itemView.setOnClickListener(onClickListener);
            // }
        }
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        private ImageView image;

        public ViewHolder(View itemView) {
            super(itemView);
            image = itemView.findViewById(R.id.img);
        }
    }
}
